package gov.kqqzyyy.monkey.pharmacyscreen.code.ui;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import gov.kqqzyyy.monkey.pharmacyscreen.R;
import gov.kqqzyyy.monkey.pharmacyscreen.code.adapter.MyGridViewAdapter;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.CurrentVersion;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.PharmacyWindowBaseActivity;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.SpeakTool;
import gov.kqqzyyy.monkey.pharmacyscreen.code.object.Patient;

//西药房屏幕
public class WMScreenActivity extends PharmacyWindowBaseActivity {

    @BindView(R.id.wm_window_text)
    TextView mWindowText;
    @BindView(R.id.wm_date_text)
    TextView mTimeText;
    @BindView(R.id.wm_prepared_patients_gridview)
    GridView mPreparedGridView;
    @BindView(R.id.wm_passed_patients_gridview)
    GridView mPassedGridView;
    @BindView(R.id.wm_waiting_patients_gridview)
    GridView mWaitingGridView;
    @BindView(R.id.wm_version_text)
    TextView mVersionText;

    private MyGridViewAdapter mPreparedAdapter;
    private MyGridViewAdapter mWaitingAdapter;
    private MyGridViewAdapter mPassedAdapter;
    private List<Patient> preparedList;

    private String mWindowID;
    private String mPharmacyID;
    private String mWindowName;

    private CallThread callThread;
    private MyHandler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wmscreen_v2);
        ButterKnife.bind(this);
        onBindUI();
        handler = new MyHandler(this);

        int textSize = 40;
        int textColor = R.color.colorGray;
        mPreparedAdapter = new MyGridViewAdapter(this);
        mPreparedAdapter.setTextSize(textSize);
        mWaitingAdapter = new MyGridViewAdapter(this);
        mWaitingAdapter.setTextSize(textSize);
        mWaitingAdapter.setTextColor(textColor);
        mPassedAdapter = new MyGridViewAdapter(this);
        mPassedAdapter.setTextColor(textColor);
        mPassedAdapter.setTextSize(textSize);
        mWaitingGridView.setAdapter(mWaitingAdapter);
        mPreparedGridView.setAdapter(mPreparedAdapter);
        mPassedGridView.setAdapter(mPassedAdapter);
    }

    @Override
    protected void onBindUI() {
        super.onBindUI();
        setTimeTextView(mTimeText);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mWindowName = getmSharedPreferences().getString("window_name", "");
        mWindowID = getmSharedPreferences().getString("window_preference", "");
        mPharmacyID = getmSharedPreferences().getString("pharmacy_preference", "");
        if (mWindowName.equals("")) {
            Toast.makeText(getApplicationContext(), "请先设置药房窗口！", Toast.LENGTH_SHORT).show();
        } else {
            mWindowText.setText(mWindowName);
        }
    }

    @Override
    public void doSetVersion() {
        super.doSetVersion();
        String text = "版本号：" + CurrentVersion.getVerName(this);
        mVersionText.setText(text);
    }


    @Override
    public void doFlushData() {
        super.doFlushData();
        doGetPatients(Integer.valueOf(mPharmacyID), mWindowID, false);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (callThread != null && callThread.isAlive()) {
            callThread.destorySpeak();
            callThread.interrupt();
            callThread = null;
        }
    }

    @Override
    protected void doFilterData() {
        super.doFilterData();
        List<Patient> patientList = getmResultList();
        if (patientList != null) {
            List<Patient> waittingList = new ArrayList<>();
            preparedList = new ArrayList<>();
            List<Patient> passedList = new ArrayList<>();
            Calendar calendar = Calendar.getInstance();
            String showDate = getShowDate();
            try {
                Date rightDate = getMyApplication().getSdfWeekDay().parse(showDate);
                calendar.setTime(rightDate);
                calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), calendar.get(Calendar.HOUR), calendar.get(Calendar.MINUTE) - 2, calendar.get(Calendar.SECOND));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            for (Patient patient : patientList
                    ) {
                if (patient.getPYBZ().equals("-1.0") || patient.getPYBZ().equals("0.0")) {//配药中
                    waittingList.add(patient);
                } else {
                    if (patient.getPYBZ().equals("1.0") && (patient.getFYBZ().equals("0.0") || patient.getFYBZ().equals("-1.0"))) { //配好药,未发药
                        try {
                            Date date = getMyApplication().getTsdfDateTime().parse(patient.getPYWCSJ());
                            if (date.getTime() < calendar.getTimeInMillis()) {
                                passedList.add(patient);
                            } else {
                                preparedList.add(patient);
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            mWaitingAdapter.setPatientList(waittingList);
            mPreparedAdapter.setPatientList(preparedList);
            mPassedAdapter.setPatientList(passedList);
        }
        if (preparedList.size() > 0 && getmSharedPreferences().getBoolean("window_of_call", false)) {
            doCallPatients();
        } else {
            new CountDownTimer(8000, 4000) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    doFlushData();
                }
            }.start();
        }
    }

    @Override
    protected void doRollingGridView() {
        super.doRollingGridView();
        rollingGridView(mPreparedGridView, 1);
        rollingGridView(mWaitingGridView, 1);
        rollingGridView(mPreparedGridView, 1);
    }

    //呼叫病人操作
    protected void doCallPatients() {
        callThread = new CallThread();
        callThread.start();
    }

    //呼叫病人线程
    private class CallThread extends Thread {

        SpeakTool speakTool;

        void destorySpeak() {
            if (speakTool != null) {
                speakTool.stop();
                speakTool.destory();
            }
        }

        @Override
        public void run() {
            super.run();
            speakTool = new SpeakTool(getApplicationContext());
            for (Patient patient : preparedList
                    ) {
                if (patient.getJHPB().equals("0.0")) {
                    Message message = new Message();
                    message.what = 0x29;
                    message.arg1 = patient.getPDHM();
                    handler.sendMessage(message);

                    speakTool.speak("      ");
                    SystemClock.sleep(1000);

                    String speakMessage = "请 " + patient.getPDHM() + " 号 " + patient.getBRXM() + " 到 " + mWindowName + " 取药 ";
                    speakMessage += " " + speakMessage;
                    speakTool.speak(speakMessage);
                    doUpdateJHPB(patient);
                    SystemClock.sleep(17000);
                }
            }
            destorySpeak();
            Message message1 = new Message();
            message1.what = 0x29;
            message1.arg1 = -1;
            handler.sendMessage(message1);
            doFlushData();

        }
    }

    private static class MyHandler extends Handler {

        WeakReference<WMScreenActivity> mActivity;

        MyHandler(WMScreenActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            WMScreenActivity activity = mActivity.get();
            switch (msg.what) {
                case 0x29:
                    activity.mPreparedAdapter.setPDHM(msg.arg1);
                    break;
            }
        }
    }
}
